#!/usr/bin/env python
################################################################################
#            __  __            _   ____        _ _ ____        _              #
#           |  \/  | ___  __ _| |_| __ )  __ _| | | __ )  ___ | |_           #
#           | |\/| |/ _ \/ _` | __|  _ \ / _` | | |  _ \ / _ \| __|         #
#           | |  | |  __/ (_| | |_| |_) | (_| | | | |_) | (_) | |_          #
#           |_|  |_|\___|\__,_|\__|____/ \__,_|_|_|____/ \___/ \__|          #
#                                                                             #
#                                     by                                       #
# _______ .______       _______  _______   ______   ______   _______   _______  #
#|   ____||   _  \     |   ____||   ____| /      | /  __  \ |       \ |   ____|  #
#|  |__   |  |_)  |    |  |__   |  |__   |  ,----'|  |  |  ||  .--.  ||  |__      #
#|   __|  |      /     |   __|  |   __|  |  |     |  |  |  ||  |  |  ||   __|      #
#|  |     |  |\  \----.|  |____ |  |____ |  `----.|  `--'  ||  '--'  ||  |____      #
#|__|     | _| `._____||_______||_______| \______| \______/ |_______/ |_______|    #
#                                                                                 #
#                        Identification Core-Module                              #
#                             Modular FrameWork                                 #
#
# Coders
#
#	Justin Giorgi (rebel_kid)
#
# Debuggers
#
#	Justin Giorgi (rebel_kid)
#	Lachlan Gilmour (chilli0)
#	David Liedle (spiderbyte)
#	(Polarina)
#	(prologic)
#
################################################################################
#                                                                              #
#                               GPL Licensed                                   #
#                                                                              #
################################################################################

# Imports
import md5

# Identifies user		
def identify(globalvars, msgvars):
	
	# Get user informaion
	globalvars["cursor"].execute("select password, id, botadmin from users where user = %s", (msgvars["source"]))
	data = globalvars["cursor"].fetchone()
	send = True
	
	# Hash password
	if len(msgvars["command"]) > 1:
		hashpass = md5.new(msgvars["command"][1]).hexdigest()
	else:
		hashpass = " "
		
	if hashpass == row[0]:
		whoisreply = WhoIsReply(globalvars, msgvars["server"], row[1], row[2], msgvars["source"])
	else:
		msgvars["server"].privmsg(msgvars["source"], "I could not log you in.")
		
class WhoIsReply:
	
	def __init__(self, globalvars, server, nickid, botadmin, source):
		self.nickid = nickid
		self.botadmin = botadmin
		self.source = source
		if (server, self.nickid) not in globalvars["identified"]:
			if (server, "whoisuser") not in globalvars["special"].keys():
				globalvars["special"][(server, "whoisuser")] = self
				server.whois(source)
			else:
				server.privmsg(source, "I could not log you in at this time. Please wait a few moments and try again.")
		else:
			server.privmsg(source, "You are already logged in. To logout user the logout <user> <password> command.")
		
	def reply(self, globalvars, server, event):
		globalvars["identified"][(server, event.arguments()[2])] = (self.nickid, self.botadmin)
		server.privmsg(self.source, "You are now logged in. Logging out is manual. Use the logout <user> <password> command.")
		

# Notes nick changes in globalvars["replace"]			
def nick(globalvars, server, event):

	# Changes the replace value
	source = event.source().split('!')[0]
	new = event.target()
	if (server, source) in globalvars["replace"].keys():
		oldnick = globalvars["replace"][(server, source)]
		del globalvars["replace"](server, source)]
		globalvars["replace"][(server, new)] = oldnick
	else:
		globalvars["replace"][(server, new)] = source
		
	# Changes nick in channelnames
	for channel in globalvars["channelnames"].keys():
		if channel[0] == server and source in globalvars["channelnames"][channel]:
			index = globalvars["channelnames"][channel].index(source)
			globalvars["channelnames"][channel][index] = new
		
# Removes identified from list on part
def part(globalvars, server, event):
	
	# Message processing
	source = event.source().split("!")[0]
	channel = event.target()
	
	# Gets chanid
	globalvars["cursor"].execute("select id from channels where channame = %s", (channel))
	row = globalvars["cursor"].fetchone()
	chanid = row[0]
	
	globalvars["channelnames"][(server, chanid)].remove(source)
		
# Removes identified from list on quit
def quit(globalvars, server, event):
	
	# Message processing
	source = event.source().split("!")[0]
	
	for channel in globalvars["channelnames"].keys():
		if channel[0] == server:
			globalvars["channelnames"][channel].remove(source)
				
def autoload(globalvars):
	
	# Loads handlers
	handlers = {'nick':nick, 'part':part, 'quit':quit}
	for feature in handlers.items():
		if feature[0] not in globalvars["handlers"].keys():
			globalvars["handlers"][feature[0]] = feature[1]
			
	# Loads privmsg
	privmsg = {'identify':identify}
	for feature in privmsg.items():
		if feature[0] not in globalvars["privmsg"].keys():
			globalvars["privmsg"][feature[0]] = feature[1]
	
def load(globalvars, msgvars):
	
	# Loads handlers
	handlers = {'nick':nick, 'part':part, 'quit':quit}
	for feature in handlers.items():
		if feature[0] not in globalvars["handlers"].keys():
			globalvars["handlers"][feature[0]] = feature[1]
		else:
			msgvars["server"].privmsg(msgvars["destination"], "There is already a handler for %s." % (feature[0]))
			
	# Loads privmsg
	privmsg = {'identify':identify}
	for feature in privmsg.items():
		if feature[0] not in globalvars["privmsg"].keys():
			globalvars["privmsg"][feature[0]] = feature[1]
		else:
			msgvars["server"].privmsg(msgvars["destination"], "There is already a private message function named %s." % (feature[0]))
	return True
			
def unload(globalvars, msgvars, reloadmodule = False):
	
	# Unloads handlers
	if reloadmodule:
		handlers = {'nick':nick, 'part':part, 'quit':quit}
		for feature in handlers.items():
			if feature[0] in globalvars["handlers"].keys():
				del globalvars["handlers"][feature[0]]
			else:
				msgvars["server"].privmsg(msgvars["destination"], "I have no clue what just happened.")
			
		# Unloads privmsg
		privmsg = {'identify':identify}
		for feature in privmsg.items():
			if feature[0] in globalvars["privmsg"].keys():
				del globalvars["privmsg"][feature[0]]
			else:
				msgvars["server"].privmsg(msgvars["destination"], "I have no clue what just happened.")
			
		# Clears identified and replace
		globalvars["identified"] = []
		globalvars["replace"] = {}
		return True
		
	else:
		msgvars["server"].privmsg(msgvars["destination"], "You want to unload my what?!?! How bout I just remove your liver.")
		return False
